<template>
	<div class="recharge-wrap" :style="{height:height+'px'}">
		<div class="recharge-bind-phone-wrap fix" v-if="!payToken && user.logined && !user.phone">
			点击此处绑定手机号,确保账号安全<div class="fr bind-phone" @click="bindPhone">绑定手机 <i class="bind-phone-icon"></i></div>
		</div>
		<div class="recharge-inner-wrap">
			<div class="choose-money-wrap">
				<div style="margin-bottom: 0.75rem;">选择金额</div>
				<div class="choose-list-wrap fix">
					<div class="choose-item fl" v-for="(item,index) in moneyArr" @click="chooseMoney(item,index)" :key="index" :class="{'add-margin':(index === 1 || index === 4),'active':chooseIndex === index}">
						<div class="rmb">{{item}}元</div>
						<div class="ubi">{{item * 100}}U币</div>
					</div>
				</div>
				<div class="ohter-money-input-wrap" :class="{'input-focus':inputFocus}">
					<input type="text" class="ohter-money-input" v-input placeholder="其他金额" novalidate="novalidate" pattern="[0-9]*"
					 v-model="money" @focus="inputFocus = true;chooseIndex = undefined" @blur="inputFocus = false">
				</div>
				<div class="account-ubi-wrap">
					到账U币：<span>{{allUbi}}U币</span>
				</div>
			</div>
			<div class="pay-type-wrap">
				<div class="pay-type-item fix">
					<div class="pay-type-left fl">微信支付</div>
					<div class="pay-type-right fr">
						<input type="radio" name="pay-type" id="wechat-pay" value="0" v-model="payChooseIndex" class="clip pay-radio">
						<label for="wechat-pay" class="pay-type-label"></label>
					</div>
				</div>
			</div>
		</div>
		<div class="pay-btn-wrap">
			<a href="javascript:;" class="pay-btn cancel-btn" @click="cancelRecharge" v-if="!payToken">取消</a>
			<a href="javascript:;" class="pay-btn" @click="goRecharge">支付</a>
		</div>
		<div class="bind-phone-outer-wrap" :class="{'active':active}" ref="bindouterwrap">
			<bind-phone :steps="nosteps" @close-bind="isActive"></bind-phone>
		</div>
		<alert-bind-phone class="recharge-loading-wrap" v-show="rechargeLoadingShow">
			<template #tips>
				<div></div>
			</template>
			<template #content>
				<div class="content">
					<div class="recharge-loading">充值中请等待<span class="dot">...</span></div>
					<div class="recharge-icon-wrap">
						<img src="@/assets/images/icon-recharge-coin.png" alt="U币">
					</div>
				</div>
			</template>
			<template #footbtn>
				<!-- 				<div class="footbtn">
					<a href="javascript:;" class="recharge-status-btn"><span>{{sendTipsMessage}}</span></a>
				</div> -->
			</template>
		</alert-bind-phone>
		<alert-bind-phone class="recharge-loading-wrap" v-show="rechargeFailShow">
			<template #tips>
				<div></div>
			</template>
			<template #content>
				<div class="content">
					<div class="recharge-loading">
						<p>网络异常！</p>
						<p>请刷新并耐心等待结果！</p>
					</div>
					<div class="recharge-icon-wrap">
						<img src="@/assets/images/icon-recharge-coin.png" alt="U币">
					</div>
				</div>
			</template>
			<template #footbtn>
				<div class="footbtn">
					<a href="javascript:;" class="recharge-status-btn" @click="refresh">刷新</a>
				</div>
			</template>
		</alert-bind-phone>
	</div>
</template>

<script>
	import mixin from '@/mixins/removeLoading'
	import input from '@/directive/input/input'
	import bindPhone from '@/views/reg/components/bindPhone'
	import axios from 'axios';
	import {
		loadStorage,
		saveStorage,
		setToken,
		removeToken
	} from '@/utils/auth'
	import {
		createNode
	} from '@/utils'
	import {
		Base64
	} from '@/utils/xchat/base64'
	import alertBindPhone from '@/views/alert_bind_phone/index'
	import {
		mapGetters
	} from 'vuex'
	import SmartScroll from '@/utils/SmartScroll'
	import {
		wxPay,
		wxPayQueryResult
	} from '@/api/pay'
	import {
		isWeixin
	} from '@/utils'
	export default {
		name: 'Recharge',
		mixins: [mixin],
		props: {
			roomId: {
				type: Number
			}
		},
		data() {
			return {
				moneyArr: [5, 20, 50, 300, 500, 1000],
				chooseIndex: undefined,
				money: undefined,
				allUbi: 0,
				inputFocus: false,
				payChooseIndex: 0,
				active: false,
				nosteps: false,
				height: undefined,
				rechargeLoadingShow: false,
				rechargeFailShow: false,
				sendTipsMessage: '',
				sendSecond: 0,
				rechargeTimer: null,
				rechargeResult: false,
				zhifuFlag: false,
				orderId: undefined,
				payToken: undefined
			}
		},
		inject: ['reload'],
		computed: {
			...mapGetters([
				'user'
			])
		},
		components: {
			bindPhone,
			alertBindPhone
		},
		directives: {
			input
		},
		methods: {
			chooseMoney(item, index) {
				this.money = item
				this.chooseIndex = index
			},
			goRecharge() {
				if (this.zhifuFlag) {
					this.$layer.open({
						content: '正在支付请勿重复操作！',
						skin: 'msg',
						time: 1
					});
					return false
				}
				if (!/(^[1-9]\d*$)/.test(Number(this.money))) {
					this.$layer.open({
						content: '充值金额必须是正整数！',
						skin: 'msg',
						time: 1
					});
					return false
				}
				// if (Number(this.money) < 5) {
				// 	this.$layer.open({
				// 		content: '充值金额不能低于5元!',
				// 		skin: 'msg',
				// 		time: 1
				// 	});
				// 	return false
				// }
				if (isWeixin && !loadStorage('openid')) {
					this.$layer.open({
						content: '在微信内置浏览器中必须微信登录后才能充值！',
						skin: 'msg',
						time: 1
					});
					return false
				}
				const index = this.$layer.open({
					type: 2,
					content: '加载中...',
				})
				this.zhifuFlag = true
				const isSafari = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)
				let param = {
					money: Number(this.money),
					room_id: this.roomId,
					is_weixin: isWeixin
				}
				if (isWeixin) {
					param.openid = loadStorage('openid')
				}
				wxPay(param).then(res => {
					this.zhifuFlag = false
					if (res.data && res.data.content) {
						// console.log(Base64.decode(res.data.content))
						this.$layer.close(index)
						this.orderId = res.data.order_id
						saveStorage('orderId', this.orderId)
						if (isWeixin) {
							this.weixinPay(JSON.parse(Base64.decode(res.data.content)), res.data.order_id)
						} else {
							let mweb_url = Base64.decode(res.data.content).match(/(http|https):\/\/([\w.]+\/?)\S*/) && Base64.decode(res.data
								.content).match(/(http|https):\/\/([\w.]+\/?)\S*/)[0].replace('amp;', '').replace(/'|"/g,'')
							let href = decodeURIComponent(mweb_url) + '&redirect_url=' + encodeURIComponent(window.location.href
								.split('?')[0] + '?tip=rechargeH5')
							window.location.href = href
						}
					}
				}).catch(err => {
					this.$layer.close(index)
					this.zhifuFlag = false
				})
			},
			bindPhone() {
				this.active = true
			},
			isActive() {
				this.active = !this.active
			},
			cancelRecharge() {
				this.$emit('close-recharge')
			},
			weixinPay(data, orderId) {
				if (typeof WeixinJSBridge == "undefined") {
					if (document.addEventListener) {
						document.addEventListener("WeixinJSBridgeReady", this.onBridgeReady(data), false);
					} else if (document.attachEvent) {
						document.attachEvent("WeixinJSBridgeReady", this.onBridgeReady(data));
						document.attachEvent("onWeixinJSBridgeReady", this.onBridgeReady(data));
					}
				} else {
					this.onBridgeReady(data, orderId);
				}
			},
			onBridgeReady(data, orderId) {
				WeixinJSBridge.invoke(
					"getBrandWCPayRequest", data,
					(res) => {
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							this.rechargeInterval(orderId)
						} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
							this.$layer.open({
								content: '支付取消！',
								skin: 'msg',
								time: 1
							});
						} else {
							this.$layer.open({
								content: '支付失败！',
								skin: 'msg',
								time: 1
							});
						}
					}
				)
			},
			refresh() {
				this.reload()
			},
			rechargeInterval(trade_no) {
				this.sendTipsMessage = '0S'
				this.rechargeLoadingShow = true
				this.rechargeTimer = setInterval(() => {
					this.sendSecond++
					this.sendTipsMessage = this.sendSecond + 'S'
					if (trade_no && this.sendSecond >= 2 && !this.rechargeResult) {
						this.rechargeResult = true
						wxPayQueryResult({
							out_trade_no: trade_no
						}).then(res => {
							//充值成功
							this.$layer.open({
								content: '充值成功！',
								skin: 'msg',
								time: 1
							});
							this.rechargeResult = false
							this.$emit('close', { success: true, coin: res.data.user_coin })
							clearInterval(this.rechargeTimer)
							this.sendSecond = 0
							this.rechargeTimer = null
							this.rechargeLoadingShow = false
							this.rechargeFailShow = false
							this.sendTipsMessage = ''
						}).catch(err => {
							this.rechargeResult = false
						})
					}
					if (this.sendSecond === 10) {
						clearInterval(this.rechargeTimer)
						this.sendSecond = 0
						this.rechargeTimer = null
						this.rechargeLoadingShow = false
						this.rechargeFailShow = true
					}
				}, 1000)
			}
		},
		watch: {
			money(val) {
				let rawVal = val
				val = Number(val)
				if (!isNaN(val)) {
					if (val > 10000) {
						this.money = rawVal.slice(0, rawVal.length - 1)
					} else {
						this.allUbi = val * 100
					}
				} else {
					this.money = rawVal.slice(0, rawVal.length - 1)
				}
			}
		},
		mounted() {
			this.height = window.innerHeight
			if (!this.$el.parentNode.dataset['bindscroll']) {
				new SmartScroll(this.$el.parentNode, this.$el)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.recharge-wrap {
		font-size: 0.87rem;
		background-color: #fff;
		height: 100%;
		overflow: auto;
		-webkit-overflow-scrolling: touch;

		.recharge-inner-wrap {
			padding: 0.62rem 1.12rem;

			.choose-list-wrap {
				.choose-item {
					width: 6.6rem;
					height: 5.62rem;
					margin-bottom: 0.62rem;
					box-sizing: border-box;
					border: 1px solid #DDDDDD;
					border-radius: 0.5rem;
					text-align: center;

					&.add-margin {
						margin: 0 calc((100vw - 2 * 1.12rem - 3 * 6.6rem) / 2);
					}

					.rmb {
						margin-top: 1.25rem;
						font-size: 1.25rem;
						color: #232323;
					}

					.ubi {
						margin-top: 0.25rem;
						font-size: 0.87rem;
						color: #999;
					}

					&.active {
						border-color: #4360F0;

						.rmb,
						.ubi {
							color: #4360F0;
						}
					}
				}
			}

			.ohter-money-input-wrap {
				border: 1px solid #DDDDDD;
				border-radius: 0.37rem;

				&.input-focus {
					border-color: #4360F0;
				}

				.ohter-money-input {
					width: 100%;
					box-sizing: border-box;
					font-size: 1rem;
					padding: 1.25rem 0.62rem;
				}
			}

			.account-ubi-wrap {
				margin-top: 1.25rem;
				font-size: 1rem;

				span {
					color: #4360F0;
				}
			}
		}

		.recharge-bind-phone-wrap {
			padding: 0 1.12rem;
			background-color: #F4F6FF;
			line-height: 3rem;
			color: #232323;
			font-size: 0.87rem;

			.bind-phone {
				color: #4360F0;

				.bind-phone-icon {
					display: inline-block;
					width: 0.75rem;
					height: 1.25rem;
					background: url(./images/bind-phone-icon.png) no-repeat center;
					background-size: contain;
					vertical-align: -0.25rem;
				}
			}
		}

		.pay-type-wrap {
			margin-top: 1.25rem;
			font-size: 1rem;
			color: #232323;

			.pay-type-item {
				position: relative;
				padding-left: 3.12rem;
				line-height: 3rem;

				&::before {
					position: absolute;
					content: '';
					width: 1.5rem;
					height: 1.5rem;
					left: 0.5rem;
					top: 0;
					bottom: 0;
					margin: auto;
					@include setFixedBackground('../../assets/images/icon-wechat-pay@2x.png');
				}

				.pay-type-label {
					display: inline-block;
					width: 1.25rem;
					height: 1.25rem;
					border: 1px solid #B0B0B0;
					background-color: #E2E2E2;
					border-radius: 50%;
					vertical-align: middle;
				}

				.pay-radio:checked+.pay-type-label {
					background: #4360F0 url('../../assets/images/icon-checkbox-gou.png') no-repeat center;
					background-size: contain;
					border-color: #4360F0;
				}
			}
		}

		.pay-btn-wrap {
			margin: 3rem 0;
			text-align: center;

			.pay-btn {
				display: inline-block;
				margin: 0 1.25rem;
				width: 6.25rem;
				line-height: 2.5rem;
				height: 2.5rem;
				border: 1px solid #4360F0;
				background-color: #4360F0;
				border-radius: 6px;
				color: #fff;
				box-sizing: border-box;
			}

			.cancel-btn {
				background-color: #fff;
				border: 1px solid #dcdfe6;
				color: #606266;
			}
		}

		.recharge-loading-wrap {
			.recharge-loading {
				color: #232323;
				font-size: 1rem;

				p {
					text-align: center;
				}
			}

			.recharge-icon-wrap {
				margin: 1.5rem 0;

				img {
					width: 2.87rem;
					height: 2.87rem;
					vertical-align: top;
				}
			}

			.recharge-status-btn {
				display: block;
				width: 4.5rem;
				height: 1.75rem;
				margin: auto;
				line-height: 1.75rem;
				background-color: #4360F0;
				border-radius: 1rem;
				color: #fff;
			}
		}
	}
</style>
